package activity.addCamera;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.hichip.campro.R;
import com.hichip.tools.HiSearchSDK;
import java.util.ArrayList;
import java.util.List;
import activity.addCamera.adapter.SearchResultListAdapter;
import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import utils.HiToast;
/**
 * 局域网搜索UID Activity
 * Created by lt on 2017\12\16 0016.
 */
public class LANSearchCameraActivity extends HiActivity {
    @BindView(R.id.titleview) TitleView titleview;
    @BindView(R.id.tv_device) TextView tv_device;
    @BindView(R.id.progressbar) ProgressBar progressbar;
    private LinearLayout layFailSearch;
    private ListView listSearchResult;
    private long oldClickTime = 0;
    private SearchResultListAdapter adapter;
    private List<HiSearchSDK.HiSearchResult> list = new ArrayList<HiSearchSDK.HiSearchResult>();
    private CountDownTimer timer;
    private HiSearchSDK searchSDK;
    private static final int isCheckData = 0 * 9995;
    private int type = 0;  //type==3是正在使用的设备跳转过来的点击Item返回 AddCameraActivity
    //type==4是正在声波配置界面跳转过来的点击Item返回 AddCameraActivity

    private String mUid;
    private int category;// category==2   点击已听见设备发出配置,LANSearchCameraActivity 里面失败提示不一样，少一个上电


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        getIntentData();
        initView();

    }

    private void getIntentData() {
        type = getIntent().getIntExtra("type", 0);
        mUid=getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        category=getIntent().getIntExtra("category",0);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_lan_search_camera;
    }

    @Override
    protected void onResume() {
        super.onResume();
        startSearch();
    }

    private void initView() {
        initTopView();
        layFailSearch = (LinearLayout) findViewById(R.id.lay_fail_lan_search);
        listSearchResult = (ListView) findViewById(R.id.list_search_result);
        adapter = new SearchResultListAdapter(this, list);
        listSearchResult.setAdapter(adapter);
        listSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position >= list.size()) return;
                HiSearchSDK.HiSearchResult r = list.get(position);
                for (MyCamera camera : HiDataValue.CameraList) {
                    if (r.uid.equalsIgnoreCase(camera.getUid())) {
                        HiToast.showToast(LANSearchCameraActivity.this, getString(R.string.tip_device_add));
                        return;
                    }
                }
                Bundle extras = new Bundle();
                extras.putString(HiDataValue.EXTRAS_KEY_UID, r.uid);
                Intent intent = new Intent();
                intent.putExtras(extras);
                if (type == 3 || type == 4) {
                    intent.setClass(LANSearchCameraActivity.this, AddCameraActivity.class);
                    intent.putExtra("type", type);
                } else {
                    intent.setClass(LANSearchCameraActivity.this, AddAndConfigWiFiActivity.class);
                    intent.putExtra("type", 2);
                }
                startActivity(intent);
            }
        });
    }

    private View listFootView;

    private void listviewAddFoot() {
        if (listSearchResult != null && listSearchResult.getFooterViewsCount() == 0) {
            listFootView = View.inflate(this, R.layout.listview_lansearch_footer, null);
            TextView tv = listFootView.findViewById(R.id.lv__tv_unsearch_device);
            tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
            tv.getPaint().setAntiAlias(true);//抗锯齿
            Animation anim = AnimationUtils.loadAnimation(LANSearchCameraActivity.this, R.anim.list_anim);
            anim.setDuration(666);
            listFootView.startAnimation(anim);
            listSearchResult.addFooterView(listFootView);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type == 4) {//声波配置跳过来,提示要不一样
                        handSoundWavesHint();
                    } else {
                        handConmmonHint();
                    }
                }
            });
        }
    }

    private void handSoundWavesHint() {
        View customView=null;
        if(category==2){
            customView = View.inflate(LANSearchCameraActivity.this, R.layout.pup_sound_waves_fail_cate2, null);
        }else {
            customView = View.inflate(LANSearchCameraActivity.this, R.layout.pup_sound_waves_fail, null);
        }
        PopupWindow popupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
        TextView tv_know = customView.findViewById(R.id.tv_know);
        tv_know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        TextView tv_try = customView.findViewById(R.id.tv_try);
        tv_try.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                Intent intent=new Intent(LANSearchCameraActivity.this,SeleApOrSoundwaveActivty.class);
                startActivity(intent);
            }
        });
    }

    private void handConmmonHint() {
        View customView=null;
        if(type==3){//type==3是正在使用的设备跳转过来的点击Item返回 AddCameraActivity
            customView=View.inflate(LANSearchCameraActivity.this,R.layout.pup_not_search_dev_3,null);
        }else {
            customView = View.inflate(LANSearchCameraActivity.this, R.layout.pup_not_search_dev, null);
        }
        PopupWindow popupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
        TextView tv_know = customView.findViewById(R.id.tv_know);
        tv_know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    private void initTopView() {
        titleview.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        titleview.setButton(TitleView.NAVIGATION_BUTTON_RIGHT);
        titleview.setRightTxt(getString(R.string.searching));
        titleview.setTitle(getString(R.string.device_list));
        titleview.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {

            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_RIGHT:
                        if (System.currentTimeMillis() - oldClickTime >= 5000) {
                            titleview.setRightTxt(getString(R.string.searching));
                            startSearch();
                            oldClickTime = System.currentTimeMillis();
                        }
                        break;
                }
            }
        });
    }

    private void startSearch() {
        titleview.setRightTxt(getString(R.string.searching));
        if (progressbar.getVisibility() == View.GONE) {
            progressbar.setVisibility(View.VISIBLE);
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        int timeLong = 20000;
        if (adapter != null) {
            list.clear();
            listSearchResult.requestLayout();
            if (listSearchResult.getFooterViewsCount() != 0 && listFootView != null) {
                listSearchResult.removeFooterView(listFootView);
            }
            adapter.notifyDataSetChanged();
        }
        searchSDK = new HiSearchSDK(new HiSearchSDK.ISearchResult() {
            @Override
            public void onReceiveSearchResult(HiSearchSDK.HiSearchResult result) {
                String temp = result.uid.substring(0, 4);
                if (!TextUtils.isEmpty(temp)) {
                    Message msg = handler.obtainMessage();
                    msg.obj = result;
                    msg.what = HiDataValue.HANDLE_MESSAGE_SCAN_RESULT;
                    handler.sendMessage(msg);
                }
            }
        });
        searchSDK.search2();
        timer = new CountDownTimer(timeLong, 1000) {
            @Override
            public void onFinish() {
                if (list == null || list.size() == 0) {
                    searchSDK.stop();
                    layFailSearch.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTick(long arg0) {
                if(arg0<=timeLong-3000){
                    titleview.setRightTxt(getString(R.string.refresh));
                }
            }
        }.start();
        layFailSearch.setVisibility(View.GONE);
        list.clear();

    }

    private Animation AnimlvItem;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SCAN_RESULT:
                    if (progressbar.getVisibility() == View.VISIBLE) {
                        progressbar.setVisibility(View.GONE);
                    }
                    listviewAddFoot();
                    HiSearchSDK.HiSearchResult searchResult = (HiSearchSDK.HiSearchResult) msg.obj;
                    if (adapter != null) {
                        list.add(searchResult);
                        listSearchResult.requestLayout();
                        adapter.notifyDataSetChanged();

                    }
                    tv_device.setVisibility(View.VISIBLE);
                    if (list != null && list.size() > 0 && layFailSearch.getVisibility() == View.VISIBLE) {
                        layFailSearch.setVisibility(View.GONE);
                    }
                    break;
                case HiDataValue.HANDLE_MESSAGE_SCAN_CHECK:
                    if (msg.arg1 == isCheckData) {
                        if (list == null || list.size() == 0) {
                            searchSDK.stop();
                            layFailSearch.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
            }

        }

    };

    // 在代码中实现列表动画
    private void startListItemAnim() {
        AnimlvItem = AnimationUtils.loadAnimation(LANSearchCameraActivity.this, R.anim.list_anim);
        LayoutAnimationController controller = new LayoutAnimationController(AnimlvItem);
        controller.setDelay(0.2f);
        controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
        listSearchResult.setLayoutAnimation(controller);
    }

    @Override
    protected void onPause() {
        super.onPause();
        searchSDK.stop();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

}
